using UnityEngine;

/// <summary>
/// 事件中心使用示例
/// </summary>
public class EventExample : MonoBehaviour
{
    // 定义一些常量作为事件名称，避免拼写错误
    public static class Events
    {
        public const string GAME_START = "GameStart";
        public const string PLAYER_HEALTH_CHANGED = "PlayerHealthChanged";
        public const string ENEMY_DEFEATED = "EnemyDefeated";
        public const string LEVEL_COMPLETED = "LevelCompleted";
    }

    void Start()
    {
        // 注册事件监听器
        EventCenter.AddListener(Events.GAME_START, OnGameStart);
        EventCenter.AddListener<int>(Events.PLAYER_HEALTH_CHANGED, OnPlayerHealthChanged);
        EventCenter.AddListener<string, int>(Events.ENEMY_DEFEATED, OnEnemyDefeated);
        
        // 触发游戏开始事件
        EventCenter.TriggerEvent(Events.GAME_START);
        
        // 模拟玩家血量变化
        EventCenter.TriggerEvent<int>(Events.PLAYER_HEALTH_CHANGED, 80);
        
        // 模拟击败敌人
        EventCenter.TriggerEvent<string, int>(Events.ENEMY_DEFEATED, "哥布林", 100);
    }

    void OnDestroy()
    {
        // 移除事件监听器，防止内存泄漏
        EventCenter.RemoveListener(Events.GAME_START, OnGameStart);
        EventCenter.RemoveListener<int>(Events.PLAYER_HEALTH_CHANGED, OnPlayerHealthChanged);
        EventCenter.RemoveListener<string, int>(Events.ENEMY_DEFEATED, OnEnemyDefeated);
    }

    #region 事件处理函数

    private void OnGameStart()
    {
        Debug.Log("游戏开始！");
    }

    private void OnPlayerHealthChanged(int health)
    {
        Debug.Log("玩家血量变化，当前血量：" + health);
    }

    private void OnEnemyDefeated(string enemyName, int reward)
    {
        Debug.Log("击败了 " + enemyName + "，获得奖励：" + reward + " 点经验值");
    }

    #endregion

    void Update()
    {
        // 按空格键触发关卡完成事件
        if (Input.GetKeyDown(KeyCode.Space))
        {
            EventCenter.TriggerEvent<string, bool, int>(Events.LEVEL_COMPLETED, "第一关", true, 500);
        }
    }

    // 可以在其他地方注册这个监听器来处理关卡完成事件
    public static void RegisterLevelCompleteHandler()
    {
        EventCenter.AddListener<string, bool, int>(Events.LEVEL_COMPLETED, OnLevelCompleted);
    }

    private static void OnLevelCompleted(string levelName, bool success, int score)
    {
        Debug.Log((success ? "成功" : "失败") + "完成 " + levelName + "，得分：" + score);
    }
}